/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <atomic_se.h>
#include <toolchain.h>
#include <cpu.h>
#include <printf.h>

uint32_t atomicAddByte(volatile uint8_t *byte, uint32_t addend)
{
    uint32_t prevVal = 0;
    uint64_t flags = 0;

    flags = cpuIntsOff();
    prevVal = *byte;
    *byte += addend;
    cpuIntsRestore(flags);

    return prevVal;
}

uint32_t atomicAdd32bits(volatile uint32_t *word, uint32_t addend)
{
    uint32_t prevVal = 0;
    uint64_t flags = 0;

    flags = cpuIntsOff();
    prevVal = *word;
    *word += addend;
    cpuIntsRestore(flags);

    return prevVal;
}

uint32_t atomicXchgByte(volatile uint8_t *byte, uint32_t newVal)
{
    uint32_t prevVal = 0;
    uint64_t flags = 0;

    flags = cpuIntsOff();
    prevVal = *byte;
    *byte = newVal;
    cpuIntsRestore(flags);

    return prevVal;
}

uint32_t atomicXchg32bits(volatile uint32_t *word, uint32_t newVal)
{
    uint32_t prevVal = 0;
    uint64_t flags = 0;

    flags = cpuIntsOff();
    prevVal = *word;
    *word = newVal;
    cpuIntsRestore(flags);

    return prevVal;
}

bool atomicCmpXchgByte(volatile uint8_t *byte, uint32_t prevVal, uint32_t newVal)
{
    uint32_t currVal;
    bool ret = 0;
    uint64_t flags;

    flags = cpuIntsOff();
    currVal = *byte;

    if (LIKELY(currVal == prevVal)) {
        *byte = newVal;
        ret = true;
    } else {
        ret = false;
    }

    cpuIntsRestore(flags);
    return ret;
}

bool atomicCmpXchg32bits(volatile uint32_t *word, uint32_t prevVal, uint32_t newVal)
{
    uint32_t currVal;
    bool ret = 0;
    uint64_t flags;

    flags = cpuIntsOff();
    currVal = *word;

    if (LIKELY(currVal == prevVal)) {
        *word = newVal;
        ret = true;
    } else {
        ret = false;
    }

    cpuIntsRestore(flags);
    return ret;
}
